package com.salary.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.salary.dao.BasicSalaryRepository;
import com.salary.entity.BasicSalary;
import com.salary.entity.dto.BasicSalaryDTO;
import com.staff.dao.StaffRepository;
import com.staff.entity.Staff;

@Service
@Transactional
public class BasicSalaryService implements IBasicSalaryService {
	@Autowired
	private BasicSalaryRepository basicSalaryDao;
	@Autowired
	private StaffRepository staffDao;
	
	public void saveOrUpdate(BasicSalary basicSalary) {
		basicSalaryDao.save(basicSalary);
	}

	public void delete(BasicSalary basicSalary) {
		basicSalaryDao.delete(basicSalary);
	}

	public void delete(List<Long> ids) {
		for(Long id:ids) {
			basicSalaryDao.delete(basicSalaryDao.findOne(id));
		}
	}

	public BasicSalary findOne(Long id) {
		return basicSalaryDao.findOne(id);
	}

	public List<BasicSalary> findAll() {
		return (List<BasicSalary>) basicSalaryDao.findAll();
	}
	public List<BasicSalaryDTO> findPage(){
		return null;
		
	}
	public Page<BasicSalary> findAll(Specification<BasicSalary> spec, Pageable pageable) {
		return basicSalaryDao.findAll(spec, pageable);
	}

	public Staff getStaff(Long id) {
		return basicSalaryDao.findOne(id).getStaff();
	}

	public Staff getOperator(Long id) {
		return basicSalaryDao.findOne(id).getOperator();
	}

	public BasicSalary findByStaff(Long staffId) {
		return basicSalaryDao.findByStaff(staffId);
	}

	public Page<BasicSalaryDTO> findPage(Specification<Staff> spec, Pageable pageable) {
		Page<Staff> page = staffDao.findAll(spec, pageable);
		List<BasicSalaryDTO> results = new ArrayList<BasicSalaryDTO>();
		for(Staff staff:page.getContent()) {
			BasicSalary bs = basicSalaryDao.findByStaff(staff.getId());
			results.add(new BasicSalaryDTO(bs, staff, staff.getDepartment().getName(), staff.getPosition().getName()));
		}
		return new PageImpl<BasicSalaryDTO>(results,pageable,page.getTotalElements());
	}

	public void saveOrUpdate(BasicSalaryDTO dto) {
		BasicSalary bs = new BasicSalary(dto, staffDao.findOne(dto.getCode()), null);
		Date t = new Date();
		if(dto.getId()!=null&&null!=basicSalaryDao.findOne(dto.getId())) {
			bs.setUpdateTime(t);
			bs.setCreateTime(basicSalaryDao.findOne(dto.getId()).getCreateTime());
		}else {
			bs.setCreateTime(t);
		}
		basicSalaryDao.save(bs);
	}


}
